clear all; close all; clc;
% img = rgb2gray(imread('zhangzifeng.png'));
% [gx gy] = imgradientxy(img, 'intermediate');
% %imshow((gx + 4)/8);
% imshow(gx)
% 
% [Gx,Gy] = imgradientxy(img,'intermediate');
% figure(1)
% imshowpair(Gx,Gy,'montage')
% title('Directional Gradients Gx and Gy, Using Sobel Method')
% [Gmag,Gdir] = imgradient(Gx,Gy);
% figure(2)
% imshowpair(Gmag,Gdir,'montage')
% title('Gradient Magnitude (Left) and Gradient Direction (Right)')
% img = rgb2gray(imread('zhangzifeng.png'));
% [Gmag2,Gdir2] = imgradient(img,'intermediate');
patch2=[82,85,83,46,44,74;
       89,95,77,41,62,102;
       97,94,56,46,82,120;
       104,82,43,67,107,130;
       106,58,51,97,135,148;
       86,45,73,126,150,157];
%patch2=[182,190,185,166,159,170;148,148,143,151,173,192;122,125,140,164,189,202;128,137,147,159,175,185;142,134,145,156,155,157;180,159,173,187,180,173]
for i=2:5
    for j=2:5
        Gx(i-1,j-1)=patch2(i+1,j)-patch2(i-1,j);
        Gy(i-1,j-1)=patch2(i,j+1)-patch2(i,j-1);
        Emag(i-1,j-1) = sqrt(Gx(i-1,j-1)^2 + Gy(i-1,j-1)^2);
        Edir(i-1,j-1) = atan(Gy(i-1,j-1)/Gx(i-1,j-1))*180/pi;
    end
end
bin = zeros(1,9);
for i=1:16
    if Edir(i)<0
        Edir(i) = Edir(i)+180;
    end
    shang = floor(Edir(i)/20)+1;
    yu    = mod(Edir(i),20);
    zuo = yu/20*Emag(i);
    you = Emag(i)-zuo;
    bin(shang)=bin(shang)+zuo;
    if shang<9
        bin(shang+1)=bin(shang+1)+you;
    else
        bin(1)=bin(1)+you;
    end
end
bar(bin)

Emag =[61.4003257320350,53.6003731330296,5.09901951359278,20.6155281280883;
       63.8122245341753,20.8806130178211,13.4536240470737,13.9283882771841;
       46.6476151587624,8.94427190999916,5.65685424949238,7.21110255092798;
       24.0208242989286,12.8062484748657,5,7.61577310586391];
Edir = [-30.3236068625500,-36.6561084159669,101.309932474020,-165.963756532074;
        -32.1957339347133,-73.3007557660064,-48.0127875041833,-158.962488974578;
        -30.9637565320735,-116.565051177078,-45,146.309932474020;
        -2.38594403038881,128.659808254090,143.130102354156,66.8014094863518];
bin = zeros(1,9);
for i=1:16
    if Edir(i)<0
        Edir(i) = Edir(i)+180;
    end
    shang = floor(Edir(i)/20)+1;
    yu    = mod(Edir(i),20);
    zuo = yu/20*Emag(i);
    you = Emag(i)-zuo;
    bin(shang)=bin(shang)+zuo;
    if shang<9
       bin(shang+1)=bin(shang+1)+you;
    else
        bin(1)=bin(1)+you;
    end
    
end
figure(2)
bar(bin)
